<?php



/**
 * Exit the script when IN_lico_admin is not defined
 */
if (!defined('IN_lico')) {
	exit;
}


function dolog($data, $printr=true, $file=false){
	global $_SESSION, $lico;
	$debug=debug_backtrace();
	$call='';
	foreach($debug as $calldata)
		$call.=$calldata['file'].':'.$calldata['line'].":\n";
	$call=date('d.m.Y H:i:s').' CallStack: '.$call;
	if($file===false){
		echo "\n<pre align=\"left\" style=\"text-align:left !important\">";
		echo $call;
		if($printr)
			echo htmlspecialchars(print_r($data,true));
		else
			var_export($data);
		echo "</pre>\n";
	}
	else{
		$fp=fopen($file,"a");
		fputs($fp,$call.print_r($data,true));
		fclose($fp);
	}
}



/**
* Checks if the user is a search robot or not
* @author Alexander Löhner
* @author Eric Appelt
* @copyright 2011
* @return integer userid
* @since 2.9.1 / 02.03.2011
*/
function lico_IsBot($agent=false, $ip=false) {
  global $db, $_SESSION;
  
  if ($ip === false)
    $ip = $_SERVER['REMOTE_ADDR'];
  
  // use when browscap.ini is set in php.ini
  if(ini_get('browscap')) {
    if ($agent === false)
      $browser = get_browser(null, true);
    else
      $browser = get_browser(trim($agent), true);
    if(!empty($browser['crawler']) and $browser['crawler'] != '0') {
      return true;
    }
  }
  
  if ($agent === false)
    $agent = $_SERVER['HTTP_USER_AGENT'];
  
  if(lico_IsBot_Agent()) {
    if(lico_IsBot_Host(gethostbyaddr($ip))) {
      return true;
    }
    // SET IF return true when bot host address is not verified
    return true;
  }
  elseif(lico_IsFacebook($agent)) {
    return true;
  }
  return false;
}

/**
* Checks if the user agent is a search robot or not
* @author Eric Appelt
* @copyright 2011
* @return integer userid
* @since 2.9.1 / 02.03.2011
*/
function lico_IsBot_Agent($agent=false) {
  $knownbots = array(
    'bot',
    'crawl',
    'search',
    'get',
    'spider',
    'find',
    'java',
    'google',
    'yahoo',
    'ask',
    'contaxe',
    'yandex',
    'libwww-perl',
    'Feedfetcher',
    'wget',
    'GbPlugin',
    'newsbeuter',
    'check_http',
    'Syndication',
    'Feed',
    'Liferea',
    'Gist Server',
    'postrank',
    'Test Certificate',
    'urlresolver',
    'Summify',
    'Wordpress'
  );

  if ($agent === false)
    $agent = $_SERVER['HTTP_USER_AGENT'];

  foreach($knownbots as $bot) {
    if(stripos($agent, $bot) !== false) {
      return true;
    } 
  }
  return false;
}

/**
* Checks if the user host is a search robot or not
* @author Eric Appelt
* @copyright 2011
* @return integer userid
* @since 2.9.1 / 02.03.2011
*/
function lico_IsBot_Host($host) {
  if(
     strpos($host, 'googlebot.com') !== false || 
     strpos($host, 'tweetmeme.com') !== false || 
     strpos($host, 'paper.li') !== false || 
     strpos($host, 'exabot.com') !== false || 
     strpos($host, 'crawl.yahoo.net') !== false
  ) {
    return true;
  }
  return false;
}

/**
* Checks if the user agent is a facebook
* @author Eric Appelt
* @copyright 2011
* @return integer userid
* @since 2.9.1 / 02.03.2011
*/
function lico_IsFacebook($agent=false) {
  if ($agent === false)
    $agent = $_SERVER['HTTP_USER_AGENT'];
  if(stripos($agent, 'facebook') !== false) {
    return true;
  }
  return false;
}



/**
 * Escapes the string for inserting it into the database
 *
 * @access public
 * @param string The string to strip
 * @return string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */
function lico_ESC($string, $entities=0) {
	$string = trim(strip_tags($string));
	$string = str_replace("../", "", $string);
	$string = str_replace("/..", "", $string);
	$string = str_replace("..", "", $string);
	$string = str_replace("SELECT", "", $string);
	$string = str_replace("DELETE", "", $string);
	$string = str_replace("TRUNCATE TABLE", "", $string);
	$string = str_replace("DROP TABLE", "", $string);
	$string = str_replace("CREATE TABLE", "", $string);
	$string = str_replace("select", "", $string);
	$string = str_replace("delete", "", $string);
	$string = str_replace("truncate table", "", $string);
	$string = str_replace("drop table", "", $string);
	$string = str_replace("create table", "", $string);
	if ($entities == 0) {
  	if(function_exists('mysql_real_escape_string')) {
  		$string = mysql_real_escape_string($string);
  	} else {
  		$string = mysql_escape_string($string);
  	}
	} else {
	  $string = htmlspecialchars($string);
	}
	return trim($string);
} 





function lico_delcookies() {
  global $lico;
  
  setcookie("lico[pwd]", "", time()-(86400*365), "/");
  setcookie("lico[num]", "", time()-(86400*365), "/");
  
  setcookie("lico[openid_service]", "", time()-(86400*365), "/");
  setcookie("lico[openid]", "", time()-(86400*365), "/");
  setcookie("lico[merken]", "", time()-(86400*365), "/");
  
}



function lico_SetUserState($key, $state=1) {
  global $db, $aktts, $lico, $_SESSION;
  
  $upd = "UPDATE `users` SET `f_mtime`='".date("Y-m-d H:i:s", time())."', `state`='".intval($state)."' WHERE `f_key`='".intval($key)."'";
  $retu = $db->unbuffered_query($upd);
  
  $selp = "SELECT `country` FROM `persons` WHERE `f_key`='".intval($key)."' LIMIT 0,1";
  $retp = $db->getAll_assoc($selp);
  $country = strtoupper(stripslashes(trim($retp[0]['country'])));
  
  if ($country != "") {
    $selplace = "SELECT * FROM `places` WHERE `code`='".lico_ESC($country)."' LIMIT 0,1;";
    $retplace = $db->aselect($selplace);
    
    if (isset($retplace[0]['f_key']) && intval($retplace[0]['f_key']) >= 1) {
      if ($state == 1)
        $updplace = "UPDATE `places` SET `users`=`users`+1 WHERE `code`='".lico_ESC($country)."'";
      else
        $updplace = "UPDATE `places` SET `users`=`users`-1 WHERE `code`='".lico_ESC($country)."'";
      $db->query($updplace);
    } else {
      $country = "";
      $updpers = "UPDATE `persons` SET `country`='".lico_ESC($country)."' WHERE `f_key`='".lico_ESC($key)."'";
      $db->query($updpers);
    }
  }
}

function lico_SetMachineState($key, $state=1) {
  global $db, $aktts, $lico, $_SESSION;
  
  if (is_numeric($state)) {
    if (intval($state) == 1)
      $state = "YES";
    else
      $state = "NO";
  }
  
  $upd = "UPDATE `machines` SET `f_mtime`='".date("Y-m-d H:i:s", time())."', `isactive`='".lico_ESC($state)."' WHERE `f_key`='".intval($key)."'";
  $retu = $db->unbuffered_query($upd);
  
  $selp = "SELECT `country` FROM `machines` WHERE `f_key`='".intval($key)."' LIMIT 0,1";
  $retp = $db->getAll_assoc($selp);
  $country = strtoupper(stripslashes(trim($retp[0]['country'])));
  
  if ($country != "") {
    $selplace = "SELECT * FROM `places` WHERE `code`='".lico_ESC($country)."' LIMIT 0,1;";
    $retplace = $db->aselect($selplace);
    
    if (isset($retplace[0]['f_key']) && intval($retplace[0]['f_key']) >= 1) {
      if ($state == 1)
        $updplace = "UPDATE `places` SET `hostcount`=`hostcount`+1 WHERE `code`='".lico_ESC($country)."'";
      else
        $updplace = "UPDATE `places` SET `hostcount`=`hostcount`-1 WHERE `code`='".lico_ESC($country)."'";
      $db->query($updplace);
    } else {
      $country = "";
      $updpers = "UPDATE `machines` SET `country`='".lico_ESC($country)."' WHERE `f_key`='".lico_ESC($key)."'";
      $db->query($updpers);
    }
  }
}




function lico_gettimestamp() {
  global $aktts, $lico, $_SESSION;
  $ts = $aktts;
  $diffsec = ( ((float)$lico['user']['timezone'] * 60) * 60 );
  return ($ts + $diffsec);
}


function lico_getdate($ts="") {
  global $aktts, $minus, $lico, $_SESSION;
  $diffsec = ( ((float)$lico['user']['timezone'] * 60) * 60 );
  if (trim($ts) == "") {
    $ts = lico_gettimestamp();
  } else {
    $ts = ($ts - $minus) + $diffsec;
  }
  if (!is_numeric($ts))
    return false;
  else
    return date($lico['user']['dateformat'], intval($ts));
}


function lico_gettime($ts="") {
  global $aktts, $minus, $lico, $_SESSION;
  $diffsec = ( ((float)$lico['user']['timezone'] * 60) * 60 );
  if (trim($ts) == "") {
    $ts = lico_gettimestamp();
  } else {
    $ts = ($ts - $minus) + $diffsec;
  }
  if (!is_numeric($ts))
    return false;
  else
    return date($lico['user']['timeformat'], intval($ts));
}


function lico_getdatetime($ts="") {
  global $aktts, $minus, $lico, $_SESSION;
  $diffsec = ( ((float)$lico['user']['timezone'] * 60) * 60 );
  if (trim($ts) == "") {
    $ts = lico_gettimestamp();
  } else {
    $ts = ($ts - $minus) + $diffsec;
  }
  if (!is_numeric($ts))
    return false;
  else
    return date($lico['user']['dateformat']." ".$lico['user']['timeformat'], intval($ts));
}




// Browsersprache ermitteln
function lico_getLangfromBrowser() {
	global $lico, $_SESSION;
	
	$default_language = "en";
	$lang_variable = null;
	$strict_mode = true;
	// $_SERVER['HTTP_ACCEPT_LANGUAGE'] verwenden, wenn keine Sprachvariable mitgegeben wurde
	if ($lang_variable === null) {
					$lang_variable = (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])?$_SERVER['HTTP_ACCEPT_LANGUAGE']:"en_US");
	}

	// wurde irgendwelche Information mitgeschickt?
	if (empty($lang_variable)) {
					// Nein? => Standardsprache zurückgeben
					return $default_language;
	}

	// Den Header auftrennen
	$accepted_languages = preg_split('/,\s*/', $lang_variable);

	// Die Standardwerte einstellen
	$current_lang = $default_language;
	$current_q = 0;

	// Nun alle mitgegebenen Sprachen abarbeiten
	foreach ($accepted_languages as $accepted_language) {
		// Alle Infos über diese Sprache rausholen
		$res = preg_match ('/^([a-z]{1,8}(?:-[a-z]{1,8})*)'.
											 '(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i', $accepted_language, $matches);

		// war die Syntax gültig?
		if (!$res) {
						// Nein? Dann ignorieren
						continue;
		}
		
		// Sprachcode holen und dann sofort in die Einzelteile trennen
		$lang_code = explode ('-', $matches[1]);

		// Wurde eine Qualität mitgegeben?
		if (isset($matches[2])) {
						// die Qualität benutzen
						$lang_quality = (float)$matches[2];
		} else {
						// Kompabilitätsmodus: Qualität 1 annehmen
						$lang_quality = 1.0;
		}

		// Bis der Sprachcode leer ist...
		while (count ($lang_code)) {
			// mal sehen, ob der Sprachcode angeboten wird
			if (in_array (strtolower (join ('-', $lang_code)), $lico['allowed_lang'])) {
				// Qualität anschauen
				if ($lang_quality > $current_q) {
					// diese Sprache verwenden
					$current_lang = strtolower (join ('-', $lang_code));
					$current_q = $lang_quality;
					// Hier die innere while-Schleife verlassen
					break;
				}
			}
			// Wenn wir im strengen Modus sind, die Sprache nicht versuchen zu minimalisieren
			if ($strict_mode) {
							// innere While-Schleife aufbrechen
							break;
			}
			// den rechtesten Teil des Sprachcodes abschneiden
			array_pop ($lang_code);
		}
	}

	// die gefundene Sprache zurückgeben
	return $current_lang;
}


function lico_lang($file, $var, $string="") {
	global $lico, $lang, $LANGUAGE, $_SESSION;
	if (!isset($_SESSION['lang'])) {
		$_SESSION['lang'] = "en";
  }
	include($lico['lang_path'].strtoupper(trim($_SESSION['lang']))."/".$file.".lang.inc");
	if (trim($string) != "") {
		$out = sprintf($LANGUAGE[$var], $string);
	} else {
		$out = $LANGUAGE[$var];
	}
	return $out;
}

/**
 * Make lico emit an error message and terminate the script
 *
 * @access public
 * @param string HTML code to die with
 * @return null
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */
function lico_die($msg) {
	global $lico;
		die('<html>
						<head>
							<title>! LiCo: Error !</title>
						</head>
						<body>'.$msg.'</body>
				</html>');
}


/**
 * Crypt a string with md5
 *
 * @access public
 * @param string The string to crypt
 * @return string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */
function lico_CryptPasswd($pwd) { 
	$cpwd = md5($pwd); 
	return $cpwd; 
} 



/**
 * Checks an email adress 
 *
 * @param          string $email email to test
 * @access         private
 * @return         bool
 * @author         Alexander Löhner
 * @copyright      2000-2004 by APP - Another PHP Program
 */
function lico_ValidateEmail($email) {
	$email = str_replace("\n", "", $email);
	$email = trim($email);
	$email = strtolower($email);
	$return = false;
	if (preg_match("`^[0-9a-z_\+]([-_\.\+]?[0-9a-z])*@[0-9a-z]([-\.]?[0-9a-z])*\.[a-z]{2,4}$`", $email, $check)) {
		if ( getmxrr(substr(strstr($check[0], '@'), 1), $validate_email_temp) ) {
			if(checkdnsrr(substr(strstr($check[0], '@'), 1),"ANY")) {
				$item = explode("@", $email);
				$domain = $item[1];
				if (gethostbyname($domain)) {
					$return = true;
				} elseif (gethostbyname("www.".$domain)) {
					$return = true;
				}
			}
		}
	}
	return $return;
}







/** Numeric (0-9) */
define( "PWD_ALLOW_NUM", ( 1 << 0 ));
/** lower case alphanumeric (a-z) */
define( "PWD_ALLOW_LC",  ( 1 << 1 ));
/** upper case alphanumeric (A-Z) */
define( "PWD_ALLOW_UC",  ( 1 << 2 ));
/** numeric and lower case alphanumeric (0-9,a-z) */
define( "PWD_ALLOW_DFLT", ( PWD_ALLOW_NUM | PWD_ALLOW_UC ));
/** all numeric and alphanumeric */
define( "PWD_ALLOW_ALL", ( PWD_ALLOW_NUM | PWD_ALLOW_LC  | PWD_ALLOW_UC ));

/**
 * GGenerates a random string with specific length
 *
 * @param          int $pwdLen Length of the random string
 * @param          const $usables alowed characters
 * @access         private
 * @return         string
 * @author         Alexander Löhner
 * @copyright      2000-2004 by APP - Another PHP Program
 */
function lico_GenRandomString($pwdLen=32,$usables=PWD_ALLOW_ALL) {
	$pwdSource = "";
	$STRING = "";
	if ( $usables & ( 1 << 0 ))     $pwdSource .= "1234567890";
	if ( $usables & ( 1 << 1 ))     $pwdSource .= "abcdefghijklmnopqrstuvwxyz";
	if ( $usables & ( 1 << 2 ))     $pwdSource .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	srand ((double) microtime() * 1000000);
	while (strlen($STRING) <= ($pwdLen-1)) {
		srand ((double) microtime() * 1000000);
		$STRING .= substr( $pwdSource, rand( 0, strlen( $pwdSource )), 1);
	}
	return $STRING;
}







/**
 * Strips some dangerous content out of strings
 *
 * @access public
 * @param string The string to strip
 * @return string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */
function lico_Strip($string, $leavetags=0) { 
	$string = str_replace("\t", "", $string);
	$string = str_replace("\r", "", $string);
	$string = str_replace("\n", "", $string);
	$string = str_replace("\0", "", $string);
	if ($leavetags == 0) {
		$string = strip_tags($string);
		$string = htmlspecialchars($string);
	}
	$string = trim($string);
	return $string;
} 




/**
 * Checks if user is logged in
 *
 * @access private
 * @return bool
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */
function lico_UserLoggedIn() {
	global $db, $lico;
	
	$isloggedin = false;
	if (defined('IS_installed')) {
		if (isset($lico['COOKIE']['userid']) && intval($lico['COOKIE']['userid']) >= 1) {
			$isloggedin = true;
			if (!isset($_SESSION['userid']) || intval($_SESSION['userid']) <= 0) {
				$cpassword = trim($lico['COOKIE']['password']);
				$seluser = $db->unbuffered_query_first("SELECT * FROM `".$lico['table']['users']."` WHERE `id`='".intval($lico['COOKIE']['userid'])."' AND `username`='".lico_ESC($lico['COOKIE']['username'])."' AND `password`='".lico_ESC($cpassword)."'");
				if (isset($seluser[0]) && intval($seluser[0]) >= 1) {
					$isloggedin = true;
				} else {
					$isloggedin = false;
				}
				
			}
		} else {
			$isloggedin = false;
		}
	} else {
		$isloggedin = false;
	}
	return $isloggedin;
}





/**
 * Creates and returns some boxes
 *
 * @access public
 * @return string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */
function lico_DisplayBoxContent($what='loginform') {
	global $lico, $db;
	$box = '';
	
	switch ($what) {
		
		case 'LoginForm':
			if (isset($_SESSION['isloggedin']) && $_SESSION['isloggedin'] === true) {
				$box .= "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"2\">\n";
				$box .= "	<tr>\n";
				$box .= "		<td>".$lico['LANGUAGE']['GLOBAL_LOGGED_IN_AS'].$_SESSION['username']."</td>\n";
				$box .= "	</tr>\n";
				$box .= "	<tr>\n";
				$box .= "		<td>&nbsp;</td>\n";
				$box .= "	</tr>\n";
				$box .= "	<tr>\n";
				$box .= "		<td>\n";
				
				$box .= "				<div id=\"sidebar_box\">\n";
				$box .= "					<ul id=\"sidebar_menu\">\n";
				$box .= "						<li id=\"sidebar_link\"><a href=\"".$lico['baseURL']."?c=profile\">".$lico['LANGUAGE']['USER_PROFILE']."</a></li>\n";
				$box .= "						<li id=\"sidebar_link\"><a href=\"".$lico['baseURL']."?lico[what]=logout\">".$lico['LANGUAGE']['GLOBAL_LOGOUT']."</a></li>\n";
				$box .= "					</ul>\n";
				$box .= "				</div>\n";
				
				$box .= "			</td>\n";
				$box .= "	</tr>\n";
				$box .= "</table>\n";
			} else {
				$box .= "<form name=\"loginform\" action=\"".$lico['baseURL']."?c=profile\" method=\"post\">\n";
				$box .= "<input type=\"hidden\" name=\"lico[what]\" value=\"login\" />\n";
				$box .= "	<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"2\">\n";
				$box .= "		<tr>\n";
				$box .= "			<td>".$lico['LANGUAGE']['GLOBAL_USERNAME']."</td>\n";
				$box .= "			<td width=\"53\"><input type=\"text\" name=\"lico[username]\" value=\"".(isset($lico['POST']['username'])?$lico['POST']['username']:'')."\" size=\"7\" style=\"width:100%\" /></td>\n";
				$box .= "		</tr>\n";
				$box .= "		<tr>\n";
				$box .= "			<td>".$lico['LANGUAGE']['GLOBAL_PASSWORD']."</td>\n";
				$box .= "			<td width=\"53\"><input type=\"password\" name=\"lico[password]\" value=\"".(isset($lico['POST']['password'])?$lico['POST']['password']:'')."\" size=\"7\" style=\"width:100%\" /></td>\n";
				$box .= "		</tr>\n";
				$box .= "		<tr>\n";
				$box .= "			<td colspan=\"2\" align=\"center\"><input type=\"submit\" name=\"lico[submit]\" value=\"".$lico['LANGUAGE']['GLOBAL_LOGIN']."\" /></td>\n";
				$box .= "		</tr>\n";
				$box .= "		<tr>\n";
				$box .= "			<td colspan=\"2\" align=\"center\">&nbsp;</td>\n";
				$box .= "		</tr>\n";
				$box .= "		<tr>\n";
				$box .= "			<td colspan=\"2\">\n";
				
				$box .= "				<div id=\"sidebar_box\">\n";
				$box .= "					<ul id=\"sidebar_menu\">\n";
				$box .= "						<li id=\"sidebar_link\"><a href=\"".$lico['baseURL']."?c=register\">".$lico['LANGUAGE']['GLOBAL_REGISTER']."</a></li>\n";
				$box .= "						<li id=\"sidebar_link\"><a href=\"".$lico['baseURL']."?c=password\">".$lico['LANGUAGE']['GLOBAL_PASSWORD_FORGOTTEN']."</a></li>\n";
				$box .= "					</ul>\n";
				$box .= "				</div>\n";
				
				$box .= "			</td>\n";
				$box .= "		</tr>\n";
				$box .= "	</table>\n";	
				$box .= "</form>\n";
			}
			break;
		
		
		case 'StaticPages':
			$selsp = $db->unbuffered_getAll_row("SELECT * FROM `".$lico['table']['staticpages']."` ORDER BY `sortit` ASC");
			if (isset($selsp) && is_array($selsp) && count($selsp) >= 1) {
				$box .= "				<div id=\"sidebar_box\">\n";
				$box .= "					<ul id=\"sidebar_menu\">\n";
				for ($a=0;$a<count($selsp);$a++) {
					$box .= "						<li id=\"sidebar_link\"><a class=\"sidebar_link\" href=\"".substr($lico['baseURL'], 0, strlen($lico['baseURL'])-1).stripslashes(trim($selsp[$a][1]))."\">".stripslashes(trim($selsp[$a][3]))."</a></li>\n";
				}
				$box .= "					</ul>\n";
				$box .= "				</div>\n";
			}
			break;
		
	}
	return $box;
}






/**
 * Fetches a complete Webpage from a given URI
 *
 * @access public
 * @return array
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */
function lico_GetHTML($url) { 
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url); 
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_TIMEOUT, '3');
  $output = trim(curl_exec($ch));	
  curl_close($ch);
  return $output; 
} 




/**
 * Deletes a complete directory with its contents (recursive)
 *
 * @param          string $sourcedir
 * @access         private
 * @return         array
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */
function lico_DeleteDirectory($sourcedir) {
	
	if (!is_dir($sourcedir)) {
		return @unlink($sourcedir);
	}
	
	$filearray = array();
	$sourcedir .= "/";
	$handle = @opendir($sourcedir);
	while ($eintrag = @readdir($handle)) {
		$target = $sourcedir.$eintrag;
		if (is_dir($target) && $eintrag != "." && $eintrag != "..") {
			@unlink($target);
			$slashpos = strrpos($target, "/");
			if ($slashpos) {
				$deldir = substr($target, 0, $slashpos);
				@rmdir($deldir);
			}
			$filearray[$target] = lico_DeleteDirectory($target);
			@unlink($target);
			$slashpos = strrpos($target, "/");
			if ($slashpos) {
				$deldir = substr($target, 0, $slashpos);
				@rmdir($deldir);
			}
		} elseif ($eintrag != "." && $eintrag != "..") {
			$filearray[] = $eintrag;
			@unlink($target);
			$slashpos = strrpos($target, "/");
			if ($slashpos) {
				$deldir = substr($target, 0, $slashpos);
				@rmdir($deldir);
			}
		}
	}
	@closedir($handle);
	return $filearray;
}





/**
 * Chmodes a complete directory with its contents (recursive)
 *
 * @param          string $sourcedir
 * @access         private
 * @return         array
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */
function lico_ChmodDirectory($sourcedir, $mode=777) {
	
	$filemode = '0'.$mode;
	$filemode = octdec($filemode);
	
	if (!is_dir($sourcedir)) {
		return chmod($sourcedir, $filemode);
	}
	
	$filearray = array();
	$sourcedir .= "/";
	$handle = @opendir($sourcedir);
	while ($eintrag = @readdir($handle)) {
		$target = $sourcedir.$eintrag;
		if (is_dir($target) && $eintrag != "." && $eintrag != "..") {
			@chmod($target, $filemode);
			$slashpos = strrpos($target, "/");
			if ($slashpos) {
				$chmoddir = substr($target, 0, $slashpos);
				@chmod($chmoddir, $filemode);
			}
			$filearray[$target] = lico_ChmodDirectory($target, $mode);
			@chmod($target, $filemode);
			$slashpos = strrpos($target, "/");
			if ($slashpos) {
				$chmoddir = substr($target, 0, $slashpos);
				@chmod($chmoddir, $filemode);
			}
		} elseif ($eintrag != "." && $eintrag != "..") {
			$filearray[] = $eintrag;
			@chmod($target, $filemode);
			$slashpos = strrpos($target, "/");
			if ($slashpos) {
				$chmoddir = substr($target, 0, $slashpos);
				@chmod($chmoddir, $filemode);
			}
		}
	}
	@closedir($handle);
	return $filearray;
}





/**
 * Checks one file or directory (without the contents) for write access
 *
 * @param          string $sourcedir
 * @access         private
 * @return         bool
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */
function lico_CheckWriteable($source) {
	global $lico;
	clearstatcache();
	if (!ereg("^".$lico['path']."/plugins/", $source)) {
		if (!is_writable($source)) {
			clearstatcache();
			return false;
		} else {
			clearstatcache();
			return true;
		}
		clearstatcache();
		return false;
	} else {
		return true;
	}
}




/**
 * Checks a directory and its contants for write access (recursive)
 *
 * @param          string $sourcedir
 * @access         private
 * @return         array
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */
function lico_CheckDirWriteable($source) {
	$array = array();
	
	if (!lico_CheckWriteable($source)) {
		if (!in_array($source, $array))
			$array[] = $source;
	}
	
	$filearray = array();
	$source .= "/";
	$handle = @opendir($source);
	while ($eintrag = @readdir($handle)) {
		$target = $source.$eintrag;
		if (is_dir($target) && $eintrag != "." && $eintrag != "..") {
			if (!lico_CheckWriteable($target)) {
				if (!in_array($target, $array))
					$array[] = $target;
			}
			$slashpos = strrpos($target, "/");
			if ($slashpos) {
				$checkdir = substr($target, 0, $slashpos);
				if (!lico_CheckWriteable($checkdir)) {
					if (!in_array($checkdir, $array))
						$array[] = $checkdir;
				}
			}
			$filearray[$target] = lico_CheckDirWriteable($target);
			if (!lico_CheckWriteable($target)) {
				if (!in_array($target, $array))
					$array[] = $target;
			}
			$slashpos = strrpos($target, "/");
			if ($slashpos) {
				$checkdir = substr($target, 0, $slashpos);
				if (!lico_CheckWriteable($checkdir)) {
					if (!in_array($checkdir, $array))
						$array[] = $checkdir;
				}
			}
		} elseif ($eintrag != "." && $eintrag != "..") {
			$filearray[] = $eintrag;
			if (!lico_CheckWriteable($target)) {
				if (!in_array($target, $array))
					$array[] = $target;
			}
			$slashpos = strrpos($target, "/");
			if ($slashpos) {
				$checkdir = substr($target, 0, $slashpos);
				if (!lico_CheckWriteable($checkdir)) {
					if (!in_array($checkdir, $array))
						$array[] = $checkdir;
				}
			}
		}
	}
	@closedir($handle);
	return $array;
}







/**
 * simple Textoutput
 *
 * @param string $string Der Posting-Text
 * @access private
 * @return string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */
function lico_simpleTextOut($string) {
	global $lico, $db;
	$string = trim(strip_tags($string));
	$string=str_replace ("\r", "", $string);
	$string=str_replace ("\l", "", $string);
	$string=str_replace ("\c", "", $string);
	$string=str_replace ("\s", "", $string);
	$string=str_replace("\t","&nbsp;&nbsp;",$string);
	$string=str_replace ("\n", "<br />\n", $string);
	return $string;
}






/**
 * Advanced BBCode
 *
 * @param string $string Der Posting-Text
 * @access private
 * @return string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */
function lico_TextOut($string, $striptags=true) {
	global $lico, $db;
	if ($striptags)
		$string = trim(strip_tags($string));
	else
		$string = trim($string);
	
	
	$string = eregi_replace("([ \r\n])http://([a-z0-9\._-]+\.[a-z]{2,4}[^ \r\n]+)","\\1[url]http://\\2[/url]",$string);
	$string = eregi_replace("([ \r\n])https://([a-z0-9\._-]+\.[a-z]{2,4}[^ \r\n]+)","\\1[url]https://\\2[/url]",$string);
	$string = eregi_replace("([ \r\n])ftp://([a-z0-9\._-]+\.[a-z]{2,4}[^ \r\n]+)","\\1[url]ftp://\\2[/url]",$string);
	$string = eregi_replace("([ \r\n])(www\.[a-z0-9_-]+\.[a-z]{2,4}[^ \\\"\r\n]*)","\\1[url=http://\\2]\\2[/url]",$string);
	$string = eregi_replace("^http://([a-z0-9\._-]+\.[a-z]{2,4}[^ \r\n]*)","[url]http://\\1[/url]",$string);
	$string = eregi_replace("^https://([a-z0-9\._-]+\.[a-z]{2,4}[^ \r\n]*)","[url]https://\\1[/url]",$string);
	$string = eregi_replace("^ftp://([a-z0-9\._-]+\.[a-z]{2,4}[^ \r\n]*)","[url]ftp://\\1[/url]",$string);
	$string = eregi_replace("^www\.([a-z0-9\._-]+\.[a-z]{2,4}[^ \r\n]*)","[url=http://www.\\1]www.\\1[/url]",$string);
	
	$string = eregi_replace("\\[url\\]www\.([^\\[]*)\\[img\\]www\.([^\\[\\?\\&]*)\\[/img\\]\\[/url\\]","<a class=\"link\" href=\"http://www.\\1\"><img src=\"http://www.\\2\" border=\"0\" alt=\"\" title=\"\" /></a>",$string);
	$string = eregi_replace("\\[url\\]http://([^\\[]*)\\[img\\]http://([^\\[\\?\\&]*)\\[/img\\]\\[/url\\]","<a class=\"link\" href=\"http://\\1\"><img src=\"http://\\2\" border=\"0\" alt=\"\" title=\"\" /></a>",$string);
	$string = eregi_replace("\\[url\\]www\.([^\\[]*)\\[/url\\]","<a class=\"link\" href=\"http://www.\\1\">\\1</a>",$string);
	$string = eregi_replace("\\[url\\]([^\\[]*)\\[/url\\]","<a class=\"link\" href=\"\\1\">\\1</a>",$string);
	$string = eregi_replace("\\[url=\&quot;","[url=\"",$string);
	$string = eregi_replace("\\&quot;\\]","\"]",$string);
	$string = eregi_replace("\\[url=([^\\[]+)\\]([^\\[]+)\\[\\/url\\]","<a class=\"link\" href=\"\\1\">\\2</a>",$string);
	$string = eregi_replace("\\[email\\]([^\\[]+)\\[/email\\]","<a class=\"link\" href=\"mailto:\\1\">\\1</a>",$string);
	$string = eregi_replace("\\[email=([^\\[]+)\\]([^\\[]+)\\[\\/email\\]","<a class=\"link\" href=\"mailto:\\1\">\\2</a>",$string);
	
	$string = eregi_replace("\\[list","[list",$string);
	$string = eregi_replace("\\[/list","[/list",$string);
	$string = str_replace("[list]","<ul type=square>",$string);
	$string = str_replace("[/list]","</ul>",$string);
	$string = str_replace("[list=1]","<ol type=1>",$string);
	$string = str_replace("[list=a]","<ol type=A>",$string);
	$string = str_replace("[list=A]","<ol type=A>",$string);
	$string = str_replace("[/list=1]","</ol>",$string);
	$string = str_replace("[/list=a]","</ol>",$string);
	$string = str_replace("[/list=A]","</ol>",$string);
	$string = str_replace("[*]","<li>",$string);
	$string = str_replace("[/*]","</li>",$string);
	$string = preg_replace("/\\[img\\](http(s?):\\/\\/)?((www.)?[A-Za-z0-9~._\\-\\/]+(\\.gif|\\.jpg|\\.png|\\.bmp))\\[\\/img\\]/i", "<img src=\"http\\2://\\3\" border=\"0\" alt=\"\" title=\"\" />", $string);
	$string = eregi_replace("quote\\]","quote]",$string);
	
	$string = preg_replace("`\[quote=([^\]]+)\]`is", '<div id="blockquote"><strong>\\1:</strong><br />', $string);
	$string = str_replace("[quote]",'<div id="blockquote">',$string);
	$string = str_replace("[/quote]",'</div>',$string);
	
	$string = preg_replace("/(\[)(mark)(=)([#A-Za-z0-9]+)(])(.*)(\[\/mark\])/siU", "<span style=\"background-color: \\4\">\\6</span>", $string);
	$string = preg_replace("/(\[)(c)(=)([#A-Za-z0-9]+)(])(.*)(\[\/c\])/siU", "<span style=\"color:\\4\">\\6</span>", $string);
	$string = str_replace ("[d]", "<strike>", $string);
	$string = str_replace ("[D]", "<strike>", $string);
	$string = str_replace ("[/d]", "</strike>", $string);
	$string = str_replace ("[/D]", "</strike>", $string);
	$string = str_replace ("[b]", "<b>", $string);
	$string = str_replace ("[B]", "<b>", $string);
	$string = str_replace ("[/b]", "</b>", $string);
	$string = str_replace ("[/B]", "</b>", $string);
	$string = str_replace ("[u]", "<u>", $string);
	$string = str_replace ("[U]", "<u>", $string);
	$string = str_replace ("[/u]", "</u>", $string);
	$string = str_replace ("[/U]", "</u>", $string);
	$string = str_replace ("[i]", "<i>", $string);
	$string = str_replace ("[I]", "<i>", $string);
	$string = str_replace ("[/i]", "</i>", $string);
	$string = str_replace ("[/I]", "</i>", $string);
	$string = str_replace ("[d]", "<strike>", $string);
	$string = str_replace ("[/d]", "</strike>", $string);
	$string = str_replace ("[left]", "<div align=\"left\">", $string);
	$string = str_replace ("[/left]", "</div>", $string);
	$string = str_replace ("[right]", "<div align=\"right\">", $string);
	$string = str_replace ("[/right]", "</div>", $string);
	$string = str_replace ("[block]", "<div align=\"justify\">", $string);
	$string = str_replace ("[/block]", "</div>", $string);
	$string = str_replace ("[f1]", "<span style=\"font-size:0.8em\">", $string);
	$string = str_replace ("[f2]", "<span style=\"font-size:1.0em\">", $string);
	$string = str_replace ("[f3]", "<span style=\"font-size:1.1em\">", $string);
	$string = str_replace ("[f4]", "<span style=\"font-size:1.2em\">", $string);
	$string = str_replace ("[f5]", "<span style=\"font-size:1.3em\">", $string);
	$string = str_replace ("[br]", "<br/>", $string);
	$string = str_replace ("[hr]", "<hr size=\"1\" noshade=\"noshade\" />", $string);
	$string = str_replace ("[verdana]", "<span style=\"font-family:Verdana, Arial, Helvetica, sans-serif\">", $string);
	$string = str_replace ("[arial]", "<span style=\"font-family:Arial, Helvetica, sans-serif\">", $string);
	$string = str_replace ("[courier]", "<span style=\"font-family:Courier New, Courier, monospace\">", $string);
	$string = str_replace ("[comic]", "<span style=\"font-family:Comic Sans MS\">", $string);
	$string = str_replace ("[terminal]", "<span style=\"font-family:Terminal, System\">", $string);
	$string = str_replace ("[/f]", "</span>", $string);
	$string = str_replace ("[/verdana]", "</span>", $string);
	$string = str_replace ("[/arial]", "</span>", $string);
	$string = str_replace ("[/courier]", "</span>", $string);
	$string = str_replace ("[/comic]", "</span>", $string);
	$string = str_replace ("[/f1]", "</span>", $string);
	$string = str_replace ("[/f2]", "</span>", $string);
	$string = str_replace ("[/f3]", "</span>", $string);
	$string = str_replace ("[/f4]", "</span>", $string);
	$string = str_replace ("[/f5]", "</span>", $string);
	$string = str_replace ("[blue]", "<span style=\"color:#0000FF\">", $string);
	$string = str_replace ("[/blue]", "</span>", $string);
	$string = str_replace ("[red]", "<span style=\"color:#FF0000\">", $string);
	$string = str_replace ("[/red]", "</span>", $string);
	$string = str_replace ("[green]", "<span style=\"color:#00FF00\">", $string);
	$string = str_replace ("[/green]", "</span>", $string);
	$string = str_replace ("[yellow]", "<span style=\"color:#ffff00\">", $string);
	$string = str_replace ("[/yellow]", "</span>", $string);
	$string = str_replace ("[white]", "<span style=\"color:#ffffff\">", $string);
	$string = str_replace ("[/white]", "</span>", $string);
	$string = str_replace ("[black]", "<span style=\"color:#000000\">", $string);
	$string = str_replace ("[/black]", "</span>", $string);
	$string = str_replace ("[center]", "<div align=\"center\">", $string);
	$string = str_replace ("[/center]", "</div>", $string);
	$string = str_replace ("\r", "", $string);
	$string = str_replace ("\l", "", $string);
	$string = str_replace ("\c", "", $string);
	$string = str_replace ("\s", "", $string);
	$string = str_replace("\t","&nbsp;&nbsp;",$string);
	$string = str_replace ("\n", "<br />\n", $string);
	return $string;
}






/** 
 * Calvulates the maximum alowed uploadsize
 * 
 * @access private
 * @return array
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_MaxUploadSize() { 
	$post_max_size = ini_get('post_max_size');
	$upload_max_filesize = ini_get('upload_max_filesize');
	if (eregi("G", $post_max_size)) {
		$pmfs1 = str_replace("G","",$post_max_size)." GBytes";
		$post_max_size = str_replace("G","",$post_max_size) * 1000000000;
	} elseif (eregi("M", $post_max_size)) {
		$pmfs1 = str_replace("M","",$post_max_size)." MBytes";
		$post_max_size = str_replace("M","",$post_max_size) * 1000000;
	} elseif (eregi("K", $post_max_size)) {
		$pmfs1 = str_replace("K","",$post_max_size)." KBytes";
		$post_max_size = str_replace("K","",$post_max_size) * 1000;
	}
	if (eregi("G", $upload_max_filesize)) {
		$pmfs2 = str_replace("G","",$upload_max_filesize)." GBytes";
		$upload_max_filesize = str_replace("G","",$upload_max_filesize) * 1000000000;
	} elseif (eregi("M", $upload_max_filesize)) {
		$pmfs2 = str_replace("M","",$upload_max_filesize)." MBytes";
		$upload_max_filesize = str_replace("M","",$upload_max_filesize) * 1000000;
	} elseif (eregi("K", $upload_max_filesize)) {
		$pmfs2 = str_replace("K","",$upload_max_filesize)." KBytes";
		$upload_max_filesize = str_replace("K","",$upload_max_filesize) * 1000;
	}
	if ($post_max_size == $upload_max_filesize) {
		$MAX_FILE_SIZE = $post_max_size;
		$FORMATED_MAX_FILE_SIZE = $pmfs1;
	} elseif ($post_max_size < $upload_max_filesize) {
		$MAX_FILE_SIZE = $post_max_size;
		$FORMATED_MAX_FILE_SIZE = $pmfs1;
	} elseif ($post_max_size > $upload_max_filesize) {
		$MAX_FILE_SIZE = $upload_max_filesize;
		$FORMATED_MAX_FILE_SIZE = $pmfs2;
	}
	$array['MAX_FILE_SIZE'] = $MAX_FILE_SIZE;
	$array['FORMATED_MAX_FILE_SIZE'] = $FORMATED_MAX_FILE_SIZE;
	return $array;
}





/** 
 * Gets the version string of the actual used gdlib
 * 
 * @access private
 * @return string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_getGDVersion() { 
	if (function_exists("gd_info")) { 
		$gd_info = gd_info(); 
		@reset ($gd_info); 
		while (@list ($key, $val) = @each ($gd_info)) { 
			if (eregi("ver", $key)) { 
				$STRING = $gd_info[$key]; 
				break 1; 
			} 
		} 
		$STRING = str_replace("bundled","",$STRING); 
		$STRING = str_replace("compatible","",$STRING); 
		$STRING = str_replace(" ","",$STRING); 
		$STRING = str_replace("(","",$STRING); 
		$STRING = str_replace(")","",$STRING); 
		$STRING = str_replace("<","",$STRING); 
		$STRING = str_replace(">","",$STRING); 
		$STRING = str_replace("=","",$STRING); 
		$STRING = "".$STRING; 
		$gdversion = $STRING; 
	} else { 
		ob_start(); 
		$oldllicol=error_reporting(0); 
		phpinfo(); 
		error_reporting($oldllicol); 
		$buffer=ob_get_contents(); 
		ob_end_clean(); 
		$quot1 = preg_quote('<b>GD Version</b>'); 
		$STRING=preg_replace("|(.*)(".$quot1.")(.*)|siU", "\\3", $buffer); 
		$quot2 = preg_quote('</td><td align="left">'); 
		$quot3 = preg_quote('</td></tr>'); 
		$STRING=preg_replace("|(".$quot2.")(.*)(".$quot3.")(.*)|siU", "\\2", $STRING); 
		$firstpos = strpos($STRING, "\n"); 
		$STRING = substr($STRING, 0, $firstpos); 
		if (eregi(" or higher", $STRING)) { 
			$STRING = str_replace(" or higher", "", $STRING); 
		} elseif (eregi("or higher", $STRING)) { 
			$STRING = str_replace("or higher", "", $STRING); 
		} 
		$STRING = "".$STRING; 
		$gdversion = $STRING; 
	} 
	return $gdversion; 
} 





/** 
 * Checks if gdlib supports truecolor
 * 
 * @access private
 * @return bool
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_haveTCSupport() { 
	if (function_exists("imagecreatetruecolor")) { 
		if (!$tmp = ImageCreateTrueColor (10, 10)) { 
			$tcsupport = false; 
		} else { 
			$testcolor = ImageColorAllocate ($tmp, 211, 167, 168); 
			ImageFill ($tmp, 0, 0, $testcolor); 
			$cindex = imagecolorat ($tmp, 4, 4); 
			if ($cindex != $testcolor) { 
				$tcsupport = false; 
			} else { 
				$tcsupport = true; 
			} 
			ImageDestroy($tmp); 
		} 
	} else { 
		$tcsupport = false; 
	} 
	return $tcsupport; 
} 





/** 
 * Checks if gdlib supports truetype fonts
 * 
 * @access private
 * @return bool
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_haveTTFSupport() { 
	if (function_exists("ImageTTFText")) { 
		$ttfsupport = true; 
	} else { 
		$ttfsupport = false; 
	} 
	return $ttfsupport; 
} 






/** 
 * Checks if gdlib supports xpm images
 * 
 * @access private
 * @return bool
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_haveXPMSupport() {
	if (!defined("IMG_XPM")) {
		$xpmsupport = false; 
	} else {
		if (ImageTypes() & IMG_XPM) { 
			$xpmsupport = true; 
		} else { 
			$xpmsupport = false; 
		}
	}
	return $xpmsupport; 
} 






/** 
 * Checks if gdlib supports xbm images
 * 
 * @access private
 * @return bool
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_haveXBMSupport() { 
	if (!defined("IMG_XBM")) {
		$xbmsupport = false; 
	} else {
		if (ImageTypes() & IMG_XBM) { 
			$xbmsupport = true; 
		} else { 
			$xbmsupport = false; 
		}
	}
	return $xbmsupport; 
} 






/** 
 * Checks if gdlib supports wbmp images
 * 
 * @access private
 * @return bool
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_haveWBMPSupport() { 
	if (!defined("IMG_WBMP")) {
		$wbmpsupport = false; 
	} else {
		if (ImageTypes() & IMG_WBMP) { 
			$wbmpsupport = true; 
		} else { 
			$wbmpsupport = false; 
		} 
	}
	return $wbmpsupport; 
} 






/** 
 * Checks if gdlib supports jpeg images
 * 
 * @access private
 * @return bool
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_haveJPEGSupport() { 
	if (!defined("IMG_JPG")) {
		$jpegsupport = false; 
	} else {
		if (ImageTypes() & IMG_JPG) { 
			$jpegsupport = true; 
		} else { 
			$jpegsupport = false; 
		} 
	}
	return $jpegsupport; 
} 






/** 
 * Checks if gdlib supports png images
 * 
 * @access private
 * @return bool
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_havePNGSupport() { 
	if (!defined("IMG_PNG")) {
		$pngsupport = false; 
	} else {
		if (ImageTypes() & IMG_PNG) { 
			$pngsupport = true; 
		} else { 
			$pngsupport = false; 
		} 
	}
	return $pngsupport; 
} 






/** 
 * Checks if gdlib supports gif images
 * 
 * @access private
 * @return bool
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_haveGIFSupport() { 
	if (!defined("IMG_GIF")) {
		$gifsupport = false; 
	}else {
		if (ImageTypes() & IMG_GIF) { 
			$gifsupport = true; 
		} else { 
			$gifsupport = false; 
		} 
	}
	return $gifsupport; 
} 






/** 
 * Scales an image in size
 * 
 * @param string $image complete path to the image
 * @param int $maxwidth maximum width
 * @param int $maxheight maximum height 
 * @param  int $dontrename Should the picture be renamed after resizing?
 * @access private
 * @return string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_ImageResize($image, $maxwidth=100, $maxheight=100, $dontrename=0) { 
	$lastpoint = strrpos($image, '.'); 
	$withoutext = substr($image, 0, $lastpoint); 
	$ext = substr($image, ($lastpoint+1), strlen($image)); 
	$imagedata = GetImageSize($image); 
	if ($imagedata[2] == 1)		{ $sim = ImageCreateFromGIF($image); } 
	elseif ($imagedata[2] == 2)	{ $sim = ImageCreateFromJPEG($image); } 
	elseif ($imagedata[2] == 3)	{ $sim = ImageCreateFromPNG($image); } 
	if ($imagedata[0] > $maxwidth || $imagedata[1] > $maxheight) { 
		if ($imagedata[0] > $maxwidth) { 
			$factor_width = round(($imagedata[0] / $maxwidth), 2); 
			$newwidth = $maxwidth; 
			$newheight = round(($imagedata[1] / $factor_width)); 
		} else { 
			$newwidth = $imagedata[0]; 
			$newheight = $imagedata[1]; 
		} 
		if ($newheight > $maxheight) { 
			$factor_height = round(($newheight / $maxheight), 2); 
			$newwidth = round(($newwidth / $factor_height)); 
			$newheight = $maxheight; 
		} 
	} elseif ($imagedata[0] < $maxwidth || $imagedata[1] < $maxheight) { 
		if ($imagedata[0] < $maxwidth) { 
			$factor_width = round(($maxwidth / $imagedata[0]), 2); 
			$newwidth = $maxwidth; 
			$newheight = round(($imagedata[1] * $factor_width)); 
		} else { 
			$newwidth = $imagedata[0]; 
			$newheight = $imagedata[1]; 
		} 
		if ($newheight < $maxheight) { 
			$factor_height = round(($maxheight / $newheight), 2); 
			$newwidth = round(($newwidth * $factor_height)); 
			$newheight = $maxheight; 
		} 
		if ($newwidth > $maxwidth) { 
			$factor_width = round(($newwidth / $maxwidth), 2); 
			$newwidth = $maxwidth; 
			$newheight = round(($newheight / $factor_width)); 
		} elseif ($newheight > $maxheight) { 
			$factor_height = round(($newheight / $maxheight), 2); 
			$newwidth = round(($newwidth / $factor_height)); 
			$newheight = $maxheight; 
		} 
	} else { 
		$newwidth = $imagedata[0]; 
		$newheight = $imagedata[1]; 
	} 
	
	if ($dontrename>=1) {
		$newimage = $withoutext.'.'.$ext; 
		@unlink($newimage);
	} else {
		$newimage = $withoutext.'.thumb.'.$newwidth.'x'.$newheight.'.'.$ext; 
	}
	
	if (!file_exists($newimage)) {
		if (ap_haveTCSupport()) { 
			$dim = ImageCreateTrueColor($newwidth, $newheight); 
		} else { 
			$dim = ImageCreate($newwidth, $newheight); 
			} 
		imagecopyresampled ($dim, $sim, 0, 0, 0, 0, $newwidth, $newheight, $imagedata[0], $imagedata[1]); 
		if ($imagedata[2] == 1) { 
			imageGIF($dim, $newimage); 
		} elseif ($imagedata[2] == 2) { 
			imageJPEG($dim, $newimage, 80); 
		} elseif ($imagedata[2] == 3) { 
			imagePNG($dim, $newimage); 
		} 
		imageDestroy($dim); 
	}
	imageDestroy($sim); 
	$ARRAY['image'] = $newimage;
	$ARRAY['data'] = "width=\"".$newwidth."\" height=\"".$newheight."\"";
	$ARRAY['width'] = intval($newwidth);
	$ARRAY['height'] = intval($newheight);
	return $ARRAY; 
} 





/**
 * formats the filesize string
 *
 * @param          int $bytes the number of bytes
 * @access         private
 * @return         string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */
function ap_GetFormattedBytes($bytes) {
	$spacebytes = $bytes;
	$spacekb = @round($bytes/1000,3);
	if (!isset($spacekb) OR $spacekb <= 0) {
		$spacekb = @round($bytes/1000);
	}
	$spacemb = @round((($bytes/1000)/1000),3);
	if (!isset($spacemb) OR $spacemb <= 0) {
		$spacemb = @round((($bytes/1000)/1000));
	}
	if (strlen($spacebytes) <= 6) {
		$RET = str_replace(".",",",$spacekb)." Kbyte(s)";
	} elseif (strlen($spacebytes) >= 7) {
		$RET = str_replace(".",",",$spacemb)." Mbyte(s)";
	} else {
		$RET = $spacebytes." Bytes";
	}
	return $RET;
}


/**
 * Convert megabytes to human readable format
 *
 * @param integer bytes Size in bytes to convert
 * @return string
 */
function lico_GetFormattedBytes($megabytes, $precision = 2) {
  $bytes = ($megabytes*1024*1024);
  $kilobyte = 1024;
  $megabyte = $kilobyte * 1024;
  $gigabyte = $megabyte * 1024;
  $terabyte = $gigabyte * 1024;
  
  if (($bytes >= 0) && ($bytes < $kilobyte)) {
      return $bytes . ' Bytes';

  } elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) {
      return round($bytes / $kilobyte, $precision) . ' Kilobytes';

  } elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) {
      return round($bytes / $megabyte, $precision) . ' Megabytes';

  } elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) {
      return round($bytes / $gigabyte, $precision) . ' Gigabytes';

  } elseif ($bytes >= $terabyte) {
      return round($bytes / $terabyte, $precision) . ' Terabytes';
  } else {
      return $bytes . ' Bytes';
  }
}





/** 
 * adds a plugin-function which has to be called on licory click at the end of the page load
 * 
 * @param string $plugin the id of the plugin
 * @access private
 * @return void
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_AddHookUpFunction($plugin) {
		global $lico, $db;
	$lico['endfunctions'][] = array(trim($plugin), 'HookUpFunction');
	$updateconfig = "UPDATE `".$lico['table']['config']."` SET `endfunctions`='".lico_ESC(trim(serialize($lico['endfunctions'])))."'";
	$db->unbuffered_query($updateconfig);
}







/** 
 * Removes a plugin-function
 * 
 * @param string $plugin the id of the plugin
 * @access private
 * @return void
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_RemoveHookUpFunction($plugin) {
	global $lico, $db;
	$newendfunctions = array();
	for ($a=0;$a<count($lico['endfunctions']);$a++) {
		if ($lico['endfunctions'][$a][0] != trim($plugin))
			$newendfunctions[] = $lico['endfunctions'][$a];
	}
	$updateconfig = "UPDATE `".$lico['table']['config']."` SET `endfunctions`='".lico_ESC(trim(serialize($newendfunctions)))."'";
	$db->unbuffered_query($updateconfig);
}







/** 
 * Creates formatted date strings 
 * 
 * @param integer $timestamp the unix timestamp to create a fuzzy date for
 * @access private
 * @return string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_fuzzyDate($timestamp) {
	global $lico, $db;
	if($timestamp > time()) {
		return strftime("%x, %X", $timestamp);
	} elseif($timestamp > mktime(0,0,0)) {
		return $lico['LANGUAGE']['GLOBAL_TODAY'].' '.strftime("%X", $timestamp);
	} elseif($timestamp > mktime(0,0,0) - 86400) {
		return $lico['LANGUAGE']['GLOBAL_YESTERDAY'].' '.strftime("%X", $timestamp);
	} elseif($timestamp > mktime(0,0,0) - 86400*7) {
		return strftime('%A %H:%M', $timestamp);
	} elseif($timestamp > mktime(0,0,0,1,1)) {
		return strftime('%A %x', $timestamp);
	} else {
		return strftime('%x', $timestamp);
	}
}







/** 
 * Generates a floating microtime number
 * 
 * @access private
 * @return float
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function microtime_float() {
		list($usec, $sec) = explode(" ", microtime());
		if (trim($usec)=="")
			$usec = 0;
		return ((float)$usec + (float)$sec);
}







/** 
 * Charset decoder
 * 
 * @param string $string text to decode
 * @access private
 * @return string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_charset_decode($string) {
	return preg_replace("/=\?(.*?)\?([QB])\?(.*?)\?=/sexi", 'lico_decode("\\3", "\\2")', $string);
}




/** 
 * 
 * 
 * @param string $string text to decode
 * @access private
 * @return string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_qp_decode($string) {
	$string = preg_replace("/(=\s*\r\n)/m", "", $string);
	$string = preg_replace("/(=([0-9A-F]){1,1}([0-9A-F]){1,1})/e", "chr(hexdec('\\2'.'\\3'))", $string);
	return $string;
}



/** 
 * 
 * 
 * @param string $string text to decode
 * @access private
 * @return string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_decode($data, $encoding="") {
	if (empty($encoding)) {
		$encoding = "Q";
	}
	if ($encoding == "Q") {
		return lico_qp_decode($data);
	} elseif ($encoding == "B") {
		return base64_decode($data);
	} else {
		return $data;
	}
}	






/** 
 * the opposite of htmlentities()
 * 
 * @param string $string
 * @access private
 * @return string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_unhtmlentities($string) {
	$string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
	$string = preg_replace('~&#([0-9]+);~e', 'chr(\\1)', $string);
	$trans_tbl = get_html_translation_table(HTML_ENTITIES);
	$trans_tbl = array_flip($trans_tbl);
	return strtr($string, $trans_tbl);
}






/** 
 * Pagenumber generator
 * 
 * @param integer $page actual page number
 * @param integer $maxpage maximum page count
 * @param string $url The url to add to the page-urls
 * @param string $pagelinkname the name of the get-variable for the pagevariable
 * @access private
 * @return string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function GetPages($page, $maxpages, $url, $pagelinkname="page") {
	global $lico, $db;
	
	if (!isset($pagelinkname) || trim($pagelinkname) == "") {
		$pagelinkname = "page";
	}
	$itemsperpage = intval($lico['itemsperpage']);
	$paging = "";
	if ($maxpages >= 2) {
		if (!isset($page) OR trim($page) == "" OR $page <= 0) {
			$page = 1;
		}
		if ($page > $maxpages) {
			$page = $maxpages;
		}
		$multiplicator = (($page * intval($itemsperpage)) - intval($itemsperpage));
		
		if (!isset($page) OR $page == 1) {
			$LIMIT = " LIMIT 0,".intval($itemsperpage);
		} else {
			$LIMIT = " LIMIT ".$multiplicator.",".intval($itemsperpage);
		}
		if ($page > 1) {
			$paging .= "<a href=\"".$url."&amp;".$pagelinkname."=1\">1</a> ";
			$paging .= "<a href=\"".$url."&amp;".$pagelinkname."=".($page - 10)."\">&lt;&lt;</a> ";
			$paging .= "<a href=\"".$url."&amp;".$pagelinkname."=".($page - 1)."\">&lt;</a> ";
		} elseif ($page == 1) {
			$paging .= "[1] ";
		}
		if ($maxpages >= 2) {
			for ($b=($page-5);$b<=($page+5);$b++) {
				if ($b > 1 AND $b < $maxpages) {
					if ($b == $page) {
						$paging .= "[".$b."] ";
					} elseif ($b >= ($maxpages)) {
					} else {
						$paging .= "<a href=\"".$url."&amp;".$pagelinkname."=".$b."\">".$b."</a> ";
					}
				}
			}
		}
		if ($page < $maxpages) {
			$paging .= "<a href=\"".$url."&amp;".$pagelinkname."=".($page + 1)."\">&gt;</a> ";
			$paging .= "<a href=\"".$url."&amp;".$pagelinkname."=".($page + 10)."\">&gt;&gt;</a> ";
			$paging .= "<a href=\"".$url."&amp;".$pagelinkname."=".$maxpages."\">".$maxpages."</a> ";
		} elseif ($page == $maxpages AND $page != 1) {
			$paging .= "[".$maxpages."] ";
		}
	} else {
		$LIMIT = "";
	}
	
	$return['paging'] = trim($paging);
	$return['limit'] = trim($LIMIT);
	return $return;
}






/** 
 * Generates the captcha picture and adds the actual captcha string to the session and returns the name of the captcha picture
 * 
 * @access private
 * @return string
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 * @original from Captcha v1.o9 - Copyright (c) 2006, Daniel Kauser
 */ 
function lico_GetCaptcha() {
	global $lico;
	
	$CAPTCHA_TempText = lico_GenRandomString(6, PWD_ALLOW_DFLT);
	$CAPTCHA_TempFile 	= "./tmp/captcha_".lico_GenRandomString(8, PWD_ALLOW_ALL).".png";
	$_SESSION['CAPTCHA_RndText'] = str_replace('I','E',str_replace('0','3',str_replace('1','S',str_replace('B','F',str_replace('O','P',str_replace('4','A',str_replace('D','K',$CAPTCHA_TempText)))))));
	$CAPTCHA_RandomText = $_SESSION['CAPTCHA_RndText'];
	
	$Welleneffekt 	= true;
	$Textgroesse 	= "32";
	$Texthoehe 		= "47";
	$Schriftart 	= $lico['path']."/libs/captcha/truetype.ttf";
	$bg1 			= $lico['path']."/libs/captcha/background1.png";
	$bg2 			= $lico['path']."/libs/captcha/background2.png";
	$ov1 			= $lico['path']."/libs/captcha/overlay1.png";
	$ov2			= $lico['path']."/libs/captcha/overlay2.png";
	
	mt_srand((double)microtime()*1000000);
	$Bild1 = mt_rand(1, 2); 
	switch ($Bild1) {
		case 1:
			$Grafik=imagecreatefrompng($bg1);
			$Grafikhilf=imagecreatefrompng($bg1);
			break 1;
		case 2:
			$Grafik=imagecreatefrompng($bg2);
			$Grafikhilf=imagecreatefrompng($bg2);
			break 1;
	}

	mt_srand((double)microtime()*1000000);
	$Bild2 = mt_rand(1, 2); 
	switch ($Bild2) {
		case 1:
			$Grafik2=imagecreatefrompng($ov1);
			break 1;
		case 2:
			$Grafik2=imagecreatefrompng($ov2);
			break 1;
	}	

	$textfarbe = array(
		imagecolorallocate($Grafik, 128, 128, 128),
		imagecolorallocate($Grafik, 0, 0, 0),
		imagecolorallocate($Grafik, 50, 171, 4),
		imagecolorallocate($Grafik, 128, 0, 128),
		imagecolorallocate($Grafik, 128, 128, 255),
		imagecolorallocate($Grafik, 255, 128, 128),
		imagecolorallocate($Grafik, 192, 122, 0),
		imagecolorallocate($Grafik, 250, 94, 250),
		imagecolorallocate($Grafik, 122, 146, 224),
		imagecolorallocate($Grafik, 122, 155, 180)
	);

	imagettftext($Grafik, $Textgroesse, mt_rand(-13, 13), 10, $Texthoehe+mt_rand(-7,8), $Textfarbe1 = $textfarbe[array_rand($textfarbe)] , $Schriftart, $CAPTCHA_RandomText[0]);
	imagettftext($Grafik, $Textgroesse, mt_rand(-13, 13), 45, $Texthoehe+mt_rand(-7,8), $Textfarbe2 = $textfarbe[array_rand($textfarbe)] , $Schriftart, $CAPTCHA_RandomText[1]);
	imagettftext($Grafik, $Textgroesse, mt_rand(-13, 13), 80, $Texthoehe+mt_rand(-7,8), $Textfarbe3 = $textfarbe[array_rand($textfarbe)] , $Schriftart, $CAPTCHA_RandomText[2]);
	imagettftext($Grafik, $Textgroesse, mt_rand(-13, 13), 113, $Texthoehe+mt_rand(-7,8), $Textfarbe4 = $textfarbe[array_rand($textfarbe)] , $Schriftart, $CAPTCHA_RandomText[3]);
	imagettftext($Grafik, $Textgroesse, mt_rand(-13, 13), 150, $Texthoehe+mt_rand(-7,8), $Textfarbe5 = $textfarbe[array_rand($textfarbe)] , $Schriftart, $CAPTCHA_RandomText[4]);
	imagettftext($Grafik, $Textgroesse, mt_rand(-13, 13), 191, $Texthoehe+mt_rand(-7,8), $Textfarbe6 = $textfarbe[array_rand($textfarbe)] , $Schriftart, $CAPTCHA_RandomText[5]);
	
	if ($Welleneffekt === true) {
		$stauchung = mt_rand(0,100)/400+0.10;
		$Grafikalt = $Grafik;
		$Grafik = $Grafikhilf;
		for ($i=1;$i<=65;$i++){
			imagecopy($Grafik, $Grafikalt, round((sin($i*$stauchung)*2))+3, $i, 1, $i, 230,1);
		}
		
	}
		
	imagecopy($Grafik, $Grafik2, 0, 0, 0, 0, 230, 65); 		
	imagepng($Grafik, $CAPTCHA_TempFile);
	imagedestroy($Grafik);
	
	return $CAPTCHA_TempFile;
}




function lico_ShowCaptcha() {
	global $lico;
	$captcha = lico_GetCaptcha();
	$captchaimg = "<img src=\"".$captcha."\" alt=\"Captcha! Please enter the code!\" title=\"Captcha! Please enter the code!\" />\n";
	
	$out = "<table width=\"100%\" border=\"0\" cellpadding=\"3\" cellspacing=\"0\">\n";
	$out .= "	<tr>\n";
	$out .= "		<td rowspan=\"2\" valign=\"top\" align=\"center\">".$captchaimg."</td>\n";
	$out .= "		<td valign=\"top\" align=\"left\">".$lico['LANGUAGE']['CAPTCHA_DESCRIPTION1']."</td>\n";
	$out .= "	</tr>\n";
	$out .= "	<tr>\n";
	$out .= "		<td valign=\"middle\" align=\"center\"><input type=\"text\" name=\"captcha\" value=\"\" style=\"width:99%\" /></td>\n";
	$out .= "	</tr>\n";
	$out .= "</table>\n";
	
	return $out;
}








/** 
 * Controls if the given captcha string is the correct one
 * 
 * @param string $string The captcha string
 * @access private
 * @return bool
 * @author Alexander Löhner
 * @copyright 2000- by Alexander Löhner
 */ 
function lico_CheckCaptcha($string) {
	if ((isset($string) && isset($_SESSION['CAPTCHA_RndText'])) && ($string == $_SESSION['CAPTCHA_RndText'])) {
		return true;
	} else {
		return false;
	}
}


function lico_GetTS($time) {
	$tmp = explode(" ", trim($time));
	$date = $tmp[0];
	$time = $tmp[1];
	$tmp = explode("-", $date);
	$year = intval($tmp[0]);
	$month = intval($tmp[1]);
	$day = intval($tmp[2]);
	$tmp = explode(":", $time);
	$hour = intval($tmp[0]);
	$min = intval($tmp[1]);
	$sec = intval($tmp[2]);
	$actts = (time()-(3600*2));
	$ts = mktime($hour, $min, $sec, $month, $day, $year);
	return $ts;
}

function lico_GetDiff($from, $until=0) {
	if ($until == 0)
		$actts = (time()-(3600*2));
	else {
		if (is_numeric($until))
			$actts = $until;
		else
			$actts = lico_GetTS($until);
	}
	$otherts = lico_GetTS($from);
	if ($otherts >= $actts)
		$seconds = $otherts - $actts;
	else
		$seconds = $actts - $otherts;
	return $seconds;
}



function lico_GetDurationFormated($seconds) {
  $years = floor($seconds/60/60/24/365);
  $days = $seconds/60/60/24%365;
	$hours = $seconds/60/60%24;
	$mins = $seconds/60%60;
	$secs = $seconds%60;
	$duration='';
  if($years>0) {
    if ($years >= 2)
      $duration .= $years." years ";
    else
      $duration .= $years." year ";
  }
  if($days>0) {
    if ($days >= 2)
      $duration .= $days." days ";
    else
      $duration .= $days." day ";
  }
	if($hours>0) {
    if ($hours >= 2)
      $duration .= $hours." hours ";
    else
      $duration .= $hours." hour ";
  }
	if($mins>0) {
    if ($mins >= 2)
      $duration .= $mins." minutes ";
    else
      $duration .= $mins." minute ";
  }
	if($secs>0) {
    if ($secs >= 2)
      $duration .= $secs." seconds ";
    else
      $duration .= $secs." second ";
  }
	$duration = trim($duration);
	if($duration==null) $duration = '0 seconds';
	return $duration;  
}



function lico_GetDiffFormated($from, $until=0) {
	$seconds = lico_GetDiff($from, $until);
	$duration = lico_GetDurationFormated($seconds);
	return $duration;  
}


#---------------------------------------------------------------------------------------
# FUNCTION: datediff($interval, $datefrom, $dateto, $using_timestamps = false)
# DATE CREATED: Mar 31, 2005
# AUTHOR: I Love Jack Daniels
# PURPOSE: Just like the DateDiff function found in Visual Basic
#       $interval can be:
#       yyyy   - Number of full years
#       q         - Number of full quarters
#       m         - Number of full months
#       y         - Difference between day numbers  (eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".)
#       d         - Number of full days
#       w         - Number of full weekdays
#       ww       - Number of full weeks
#       h         - Number of full hours
#       n         - Number of full minutes
#       s         - Number of full seconds (default)
#---------------------------------------------------------------------------------------
function datediff($interval, $datefrom, $dateto, $using_timestamps = false) {  
  if (!$using_timestamps) {
        $datefrom = strtotime($datefrom, 0);
        $dateto = strtotime($dateto, 0);
  }
  $difference = $dateto - $datefrom; // Difference in seconds
  switch($interval) {
        case 'yyyy': $years_difference = floor($difference / 31536000);
                                if (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom), date("j", $datefrom), date("Y", $datefrom)+$years_difference) > $dateto) {
                                        $years_difference--;
                                }
                                if (mktime(date("H", $dateto), date("i", $dateto), date("s", $dateto), date("n", $dateto), date("j", $dateto), date("Y", $dateto)-($years_difference+1)) > $datefrom) {
                                        $years_difference++;
                                }
                                $datediff = $years_difference;
                                break;
        case "q":   $quarters_difference = floor($difference / 8035200);
                                while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($quarters_difference*3), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
                                        $months_difference++;
                                }
                                $quarters_difference--;
                                $datediff = $quarters_difference;
                                break;
        case "m":   $months_difference = floor($difference / 2678400);
                                while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($months_difference), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
                                        $months_difference++;
                                }
                                $months_difference--;
                                $datediff = $months_difference;
                                break;
        case 'y':   $datediff = date("z", $dateto) - date("z", $datefrom); break;
        case "d":   $datediff = floor($difference / 86400); break;
        case "w":   $days_difference = floor($difference / 86400);
                                $weeks_difference = floor($days_difference / 7); // Complete weeks
                                $first_day = date("w", $datefrom);
                                $days_remainder = floor($days_difference % 7);
                                $odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?
                                if ($odd_days > 7) { $days_remainder--; }
                                if ($odd_days > 6) { $days_remainder--; }
                                $datediff = ($weeks_difference * 5) + $days_remainder;
                                break;
        case "ww":  $datediff = floor($difference / 604800); break;
        case "h":   $datediff = floor($difference / 3600); break;
        case "n":   $datediff = floor($difference / 60); break;
        default:        $datediff = $difference; break;
  }     
  return $datediff;
}



function lico_messages() {
	global $success, $error;
	if ((isset($success) && count($success) >= 1) || (isset($error) && count($error) >= 1)) {
		echo "        <tr>\n";
		echo "          <td align=\"center\" valign=\"top\" height=\"100\" id=\"messages\" colspan=\"3\">\n";
		if ((isset($success) && count($success) >= 1)) {
			echo "<div id=\"success\"><ul id=\"successlist\">";
			for ($i=0; $i<count($success); $i++) {
				echo "            <li>".$success[$i]."</li>\n";
			}
			echo "</ul></div>";
		}
		if ((isset($error) && count($error) >= 1)) {
			echo "<div id=\"error\"><ul id=\"errorlist\">";
			for ($i=0; $i<count($error); $i++) {
				echo "            <li>".$error[$i]."</li>\n";
			}
			echo "</ul></div>";
		}
		echo "          </td>\n";
		echo "        </tr>\n";
	}
}

function lico_getXMLArray($xml) {
	$data = trim($xml);
	$xml_parser = xml_parser_create();
	xml_parse_into_struct($xml_parser, $data, $vals, $index);
	xml_parser_free($xml_parser);

	$params = array();
	$llicol = array();
	foreach ($vals as $xml_elem) {
		if ($xml_elem['type'] == 'open') {
			if (array_key_exists('attributes',$xml_elem)) {
				list($llicol[$xml_elem['llicol']],$extra) = array_values($xml_elem['attributes']);
			} else {
				$llicol[$xml_elem['llicol']] = $xml_elem['tag'];
			}
		}
		if ($xml_elem['type'] == 'complete') {
			$start_llicol = 1;
			$php_stmt = '$params';
			while($start_llicol < $xml_elem['llicol']) {
				$php_stmt .= '[$llicol['.$start_llicol.']]';
				$start_llicol++;
			}
			$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
			eval($php_stmt);
		}
	}
	return $params;
}


function lico_GeneralStatsOverview() {
	
	
	
	
	
	
}



function lico_PercentBar($percent) {
  $percent = (float)round($percent, 2);
  $percent1 = "";
  $percent2 = "";
  
  if ($percent >= 80) {
    $percent1 = " &nbsp;".number_format($percent, 2, '.', ',')."%";
    $percent2 = "&nbsp;";
  } else {
    $percent1 = "&nbsp;";
    $percent2 = " &nbsp;".number_format($percent, 2, '.', ',')."%";
  }
  
  $out  = "<div class=\"percentbar\">\n";
  $out .= "     <div class=\"percentbar-percents\" style=\"width:".$percent."%;\">".$percent1."</div>\n";
  $out .= "     <div class=\"percentbar-rest\" style=\"width:".((100-$percent)-0.05)."%;\">".$percent2."</div>\n";
  $out .= "</div>\n";
  return $out;
}




function lico_getUptimeSeconds($uptimestring) {
  $uptime = trim($uptimestring);
  $uptime = str_replace("  ", " ", $uptime);
  $uptime = str_replace("  ", " ", $uptime);
  $uptime = str_replace("  ", " ", $uptime);
  if (is_numeric($uptime)) {
    return intval($uptime);
  } else {
    if (isset($uptime) && trim($uptime) != "") {
      if (preg_match("`^[0-9]+:[0-9]+[a-zA-Z]+`", $uptime)) {
        $tmp = explode(":", $uptime);
        $std = intval($tmp[0]);
        $min = intval(preg_replace("`([0-9]+)[a-zA-Z]+.*`", "\1", $tmp[1]));
        $uptime = (($std*60*60) + ($min*60));
      } else if (preg_match("`^[0-9]+:[0-9]+ .*`", $uptime)) {
        $tmp = explode(":", $uptime);
        $std = intval($tmp[0]);
        $tmp2 = explode(" ", $tmp[1]);
        $min = intval($tmp2[0]);
        $uptime = (($std*60*60) + ($min*60));
      } else if (preg_match("`^[0-9]+:[0-9]+$`", $uptime)) {
        $tmp = explode(":", $uptime);
        $std = intval($tmp[0]);
        $min = intval($tmp[1]);
        $uptime = (($std*60*60) + ($min*60));
      } else if (preg_match("`^[0-9]+ day[s]*$`", $uptime)) {
        $tmp = explode(" ", $uptime);
        $days = intval($tmp[0]);
        $uptime = ($days*24*60*60);
      } else if (preg_match("`^[0-9]+ day[s]* [0-9]+:[0-9]+$`", $uptime)) {
        $tmp = explode(" ", $uptime);
        $days = intval($tmp[0]);
        $tmp2 = explode(":", $tmp[2]);
        $std = intval($tmp2[0]);
        $min = intval($tmp2[1]);
        $uptime = (($days*24*60*60) + ($std*60*60) + ($min*60));
      } else if (preg_match("`^[0-9]+ min[s]*$`", $uptime)) {
        $tmp = explode(" ", $uptime);
        $min = intval($tmp[0]);
        $uptime = ($min*60);
      }
    }
  }
  return $uptime;
}

function lico_getUptimeFormatted($uptimestring) {
  $uptime = lico_getUptimeSeconds($uptimestring);
  $uptime = lico_GetDurationFormated($uptime);
  return $uptime;
}




































?>
